package com.kongyz;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author kongyz
 * @date 2018/7/19 22:03
 * @Description:
 */
public class ConnectionWatcher implements Watcher {
    private static final int SESSION_TIMEOUT=5000;
    public ZooKeeper zk;
    private CountDownLatch connectedSignal=new CountDownLatch(1);

    /**
     * 链接zookeeper
     * @param hosts
     * @throws IOException
     * @throws InterruptedException
     */
    public void connect(String hosts) throws IOException, InterruptedException {
        zk=new ZooKeeper(hosts, SESSION_TIMEOUT, this);
        connectedSignal.await();
    }

    /**
     * 链接成功后的回调事件
     * @param watchedEvent
     */
    public void process(WatchedEvent watchedEvent) {
        if(watchedEvent.getState()== Event.KeeperState.SyncConnected){
            connectedSignal.countDown();
        }
    }

    /**
     * 关闭zookeeper
     * @throws InterruptedException
     */
    public void close() throws InterruptedException {
        zk.close();
    }
}
